// pages/Settlement/Offline/Offline.js
const controllers = require('../../controllers/controllerIndex.js').controller;
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    index:0,
    selectItem:{
      mobile:"",
      nick:"",
      chooseProduct:[]
    },
    remarkContent:"",
    showAdd:true,
    remark:"",
    input:null,
    chooseProduct:[],
    input:null,
    customList:[],
    typeList:[
      {
        name:"商品",
        type:1
      },
      {
        name:"服务",
        type:0
      }
    ],
    dialogShow:false,
    buttons: [{text: '取消'}, {text: '确定'}],
    customPrice:"",
    subMoney:"",
    haveServe:false,
    showModalStatus:false,
    isOpenBean:true,
    openBean:1
  },

  switchOpenBean(e){
    this.setData({
      isOpenBean: e.detail.value,
    })
    if(this.data.isOpenBean==false){
      this.setData({
        openBean:0
      })
    }else{
      this.setData({
        openBean:1
      })
    }
  },

  bindKeyInput(res) {
    console.log(res)
    this.setData({
      input: res.detail.value
    })
  },

  //删除商品
  delete(e){
    let index=e.currentTarget.dataset.index
    let list=this.data.chooseProduct
    list.splice(index,1)
    this.setData({
      chooseProduct:list
    })
    this.Statistics()
  },

  //减少商品
  mins(e){
    let index=e.currentTarget.dataset.index
    let list=this.data.chooseProduct
    if(list[index].count<=1){
      list.splice(index,1)
    }else{
      list[index].count=list[index].count-1
    }
    this.setData({
      chooseProduct:list
    })
    this.Statistics()
  },

  //增加商品
  plus(e){
    let index=e.currentTarget.dataset.index
    let list=this.data.chooseProduct
    list[index].count=list[index].count+1
    this.setData({
      chooseProduct:list
    })
    this.Statistics()
  },

  // bindPickerChange(res){
  //   let name =this.data.peopleList[res.detail.value].nick
  //   let shopAccountId=this.data.peopleList[res.detail.value].id
  //   this.setData({
  //     choosePeople:name,
  //     shopAccountId:shopAccountId
  //   })
  // },
  cancel() {
    wx.navigateBack({

    })

  },
  //新增自定义项目
  addCustom(){
    let value={'num':1,'price':'','name':'','type':1}
    let list=this.data.customList
    list.push(value)
    this.setData({
      customList:list
    })
    this.judgeHaveServe()
  },
  //获取input输入
  getInput(e){
    let index=e.currentTarget.dataset.index
    let type=e.currentTarget.dataset.type
    let value=e.detail.value

    let list=this.data.customList
    if(type=="name"){
      list[index].name=value
    }else if(type=="num"){
      list[index].num=value
    }else if(type=="price"){
      list[index].price=value
    }
    this.setData({
      customList:list
    })

    this.Statistics()
  },

  //自定义项目选择类型
  bindTypeChange(e){
    let index=e.currentTarget.dataset.index
    let selectIndex=e.detail.value
    let type=this.data.typeList[selectIndex].type
    let list=this.data.customList
    list[index].type=type
    this.setData({
      customList:list
    })
    this.judgeHaveServe()
    this.Statistics()
  },

  clickBtn(res) {

    let index = this.data.chooseProduct.findIndex(item => {
      return item.id == res.detail;
    });
    let preReplace = this.data.chooseProduct;
    if (index != -1) {
      preReplace.splice(index, 1);
    }
    this.setData({
      chooseProduct: preReplace
    })

  },
  optionTap(res) {
    var that = this;
    controllers.selectByMobile({
      sessionId: wx.getStorageSync('token'),
      shopId: wx.getStorageSync('shopId'),
      mobile: this.data.input
    }).then(res => {
      that.setData({
        userList: res.data
      })

    })
  },

  selectUser(res){
  
  
   this.setData({
     selectId: res.currentTarget.dataset.item.id,
     selectItem: res.currentTarget.dataset.item,
     show:false,
     showAdd:true
   })
  },
  remarkInput(res){
    this.setData({
      remark:res.detail.dataset
    })
  },
  addproduct() {
      if(this.data.haveGoods){
        wx.showToast({
          title: '该店铺无商品可添加',
        })
      }
    let nowListSting = JSON.stringify(this.data.chooseProduct);
    wx.navigateTo({
      url: '/pages/settlement/AddGoods/AddGoods?nowList=' + nowListSting,
    })
  },

  onAddAccount() {
    let mobile = this.data.input||"";
    let url = '/pages/userStatistics/UserEdit/UserEdit?callback=onAccountResult&mobile='+mobile;
    wx.navigateTo({url:url})
  },
  onAccountResult(res) {
    let that = this;
    let params={
      sessionId: wx.getStorageSync('token'),
      shopId:wx.getStorageSync('shopId'),
      accountRelationId:res.id
    }
    controllers.accountDetail(params).then((res)=>{//转换对象
      let data = res.data;
      let item = {
        id:data.id,
        mobile:data.accountMobile,
        nick:data.accountNick
      };
      that.setData({
        selectId: item.id,
        selectItem: item,
        show:false
      });
    });

  },

  showPopup() {
    this.setData({
      show: true
    });
  },

  onClose() {
    this.setData({
      show: false
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.initWatch(this)

    if(options.accountRelationId){
      this.setData({
        'selectItem.mobile':options.accountMobile,
        'selectItem.nick':options.accountNick,
        'selectItem.id':options.accountRelationId,
        vip:options.vip
      })
    }
   console.log(options); 
   let value=JSON.parse(options.detail||null);
   console.log(value);
   if(value){
     value.goods.count=1;
     let goods=[];
     goods.push(value.goods)
     this.setData({
       'selectItem.mobile':value.accountMobile,
       'selectItem.nick':value.accountNick,
       'selectItem.id':value.accountRelationId,
       chooseProduct:goods,
       showAdd:false,
       remarkContent:value.desc,
       remark:value.desc
     })
   }
  controllers.getStaffList({
      sessionId: wx.getStorageSync('token'),
      shopId:wx.getStorageSync('shopId')
    }).then(res =>{
      this.setData({
        peopleList: res.data
      })
     
    })
    controllers.haveGoods({
      shopId: wx.getStorageSync('shopId'),
      
    }).then(res =>{
      let have=res.data.id==null
      this.setData({
        haveGoods: have
      })
    })
  },
  confirm(){
    let that =this
    let goodsIdNum=""
    
    console.log(this.data.customList)
    console.log(this.data.chooseProduct)
    if(!this.data.selectItem.id){
      wx.showToast({
        icon:"none",
        title: '请选择用户',
      })
      return
    }
    if(this.data.chooseProduct.length<=0&&this.data.customList.length<=0){
        wx.showToast({
          icon:"none",
          title: '请添加商品或新增自定义项目',
        })
        return
      }
      if(this.data.customList.length>0){
        let index=0
        this.data.customList.forEach(item=>{
          if(!item.price||!item.name){
            index++
          }
        })
        if(index>0){
          wx.showToast({
            icon:"none",
            title: '请填写完整自定义项目'
          })
          return
        }
      }
      // if(this.data.haveServe==true){
      //   if(!this.data.currentDate){
      //     wx.showToast({
      //       icon:"none",
      //       title: '请选择预约日期'
      //     })
      //     return
      //   }
      //   if(!this.data.currentTime){
      //     wx.showToast({
      //       icon:"none",
      //       title: '请选择预约时间'
      //     })
      //     return
      //   }
      // }
        this.setData({
          dialogShow:true
        })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
   // onShareAppMessage: function () {

  // }

  //统计商品数和价格
  Statistics(){
    let price=0
    let num=0
    let chooseProduct=this.data.chooseProduct
    let customList=this.data.customList

    chooseProduct.forEach(item=>{
      let goodsPrice=''
      if((this.data.vip==1||this.data.vip==3) && item.vipState==1){
        goodsPrice=item.vipPrice;
      }else if((this.data.vip==1||this.data.vip==3) && item.vipState==0&&item.memberState==1){
        goodsPrice=item.memberPrice;
      }else if(this.data.vip==2&&item.memberState==1){
        goodsPrice=item.memberPrice;
      }else{
        goodsPrice=item.price;
      }

      price=price+goodsPrice*item.count
      num=num+item.count
    })

    customList.forEach(item=>{
      if(item.price){
        price=price+parseFloat(item.price)*item.num
        num=num+item.num
      }
    })
    this.setData({
      totalPrice:price,
      CustomPrice:price,
      totalNum:num
    })
    this.getCouponMoney()
  },

  //删除自定义项目
  delProject(e){
    let index=e.currentTarget.dataset.index
    let list=this.data.customList
    list.splice(index,1)
    this.setData({
      customList:list
    })
    this.judgeHaveServe()
    this.Statistics()
  },

  //打开确认弹框
  tapDialogButton(e){
    let index=e.detail.index
    let that =this
    let goodsIdNum=""
    console.log(e)
    if(index==1){
      this.data.chooseProduct.forEach((item,index) =>{
        let end=(index==that.data.chooseProduct.length-1)?"":","
        goodsIdNum=goodsIdNum+item.id+"-"+item.count+end
        
      })
     let shopAccountId= that.data.staffId
   let json ={
    payMoney:this.data.CustomPrice,
    goodsIdNum:goodsIdNum,
    sessionId: wx.getStorageSync('token'),
    shopId:wx.getStorageSync('shopId'),
    otherGoods:JSON.stringify(this.data.customList),
    openBean:this.data.openBean
   }
  
   if( this.data.selectItem){
    json.accountRelationId=that.data.selectItem.id
   }
  //  if(this.data.haveServe){
  //   json.agreeTime=this.data.currentDate+" "+this.data.currentTime
  //  }
  
   if(shopAccountId){
    json.shopAccountId=shopAccountId
   }
  if(that.data.remark){
        json.desc=that.data.remark}
  
   controllers.saveOrder(json).then(res =>{
    if(res.code==1){
      const that = this;
      const pages = getCurrentPages();
      const beforePage = pages[pages.length - 2];  
      wx.showToast({
        title: '开单成功',
        duration: 1000,
        success: function () {
        // setTimeout(function () {
        //   wx.navigateTo({
        //     url: 'pages/order/OrderRecord/OrderRecord',
        //   })
        // }, 1000);
       }
     })
     setTimeout(function(){
        wx.navigateTo({
          url: '/pages/settlement/Offline/OfflineSuccess/OfflineSucces?id='+res.data.id,
        })
     },1000)
  
    }
   
  })
    }else{

    }
    this.setData({
      dialogShow:false
    })
  },

  watch:{
    "chooseProduct":function(){
      this.Statistics()
    }
  },

  //获取自定义价格
  getCustomPrice(e){
    let value=e.detail.value
    this.setData({
      CustomPrice:value
    })
    this.getCouponMoney()
  },

  //获取优惠金额
  getCouponMoney(){
    this.setData({
      subMoney:this.data.totalPrice-(this.data.CustomPrice||0)
    })
  },

  //选择预约日期
  selectDate(e){
    this.setData({
      currentDate:e.detail.value
    })
  },

  //选择预约时间
  selectTime(e){
    this.setData({
      currentTime:e.detail.value
    })
  },

  //判断是否有自定义服务
  judgeHaveServe(){
    let list=this.data.customList
    let index=0
    for(let i=0;i<list.length;i++){
      if(list[i].type===0){
        index++
      }
    }
    if(index>0){
      this.setData({
        haveServe:true
      })
    }else{
      this.setData({
        haveServe:false
      })
    }
  },


  //关闭员工选框
  closeOpen(){
    this.setData({
      staffBox:false
    })
  },

  //显示弹框
  showModal: function() {
    this.setData({
      showModalStatus: true
    })
  },
  // 隐藏弹框
  hideModal: function() {
      this.setData({
        showModalStatus: false
      })
  },

  //选择员工
  selectStaff(e){
    let index=e.currentTarget.dataset.index
    console.log(e)
    if(index===this.data.selectIndex){
      this.setData({
        selectIndex:"",
        staffId:"",
        staffName:""
      })
    }else{
      this.setData({
        selectIndex:index
      })
    }
  },

  //确定员工
  defineStaff(){
    if(this.data.selectIndex||this.data.selectIndex===0){
      this.setData({
        staffId:this.data.peopleList[this.data.selectIndex].id,
        staffName:this.data.peopleList[this.data.selectIndex].nick
      })
    }
    this.hideModal()
  },

  //跳转员工详情
  selectStaffDetail(e){
    let id=e.currentTarget.dataset.id
    let index=e.currentTarget.dataset.index
    let value=this.data.peopleList[index]
    wx.navigateTo({
      url: '/pages/selecStaffDetail/selecStaffDetail?staffDetail='+encodeURIComponent(JSON.stringify(value)),
    })
  }
})


